import { getPerformancePeriodList } from '@/api'
import { DatePeriod } from '@/types/common'
import { FormControlProps } from '@mui/material'

const MenuProps = {
  PaperProps: {
    style: {
      maxHeight: 200
    }
  }
}
type Props = {
  period: DatePeriod
  setPeriod: (period: DatePeriod) => void
  [key: string]: any
} & FormControlProps

const PeriodSelector = ({ period: selectedPeriod, setPeriod: setSelectedPeriod, ...rest }: Props) => {
  const { data } = useRequest(getPerformancePeriodList, {
    cacheKey: '/performance/period/list',
    onSuccess(data) {
      const period = data?.data?.at(-1)
      if (period) {
        setSelectedPeriod(period)
      }
    }
  })
  const handlePeriodChange = (period: DatePeriod) => () => {
    setSelectedPeriod(period)
  }
  return (
    <FormControl fullWidth size="small" {...rest}>
      <Select id="period-selector" value={selectedPeriod.start_date} MenuProps={MenuProps}>
        {(data?.data ?? []).map((period, index) => (
          <MenuItem key={index} value={period.start_date} onClick={handlePeriodChange(period)}>
            <Typography variant="button">
              {period.start_date} - {period.end_date}
            </Typography>
          </MenuItem>
        ))}
      </Select>
    </FormControl>
  )
}

export default PeriodSelector
